package com.qf.kk.servlet;
/*
 *@author KK on 2022.09.14 13:09
 */

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.*;

@WebServlet("/upload")
@MultipartConfig()
public class Upload extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取上传文件对象
        Part file = req.getPart("file");
        //获取文件名
        String fileName = file.getSubmittedFileName();
        //上传文件输入流
        InputStream inputStream = file.getInputStream();
        //获取项目部署路径下的upload文件夹
        String realPath = req.getServletContext().getRealPath("/upload");
        //使用部署路径创建新的文件夹
        File file1 = new File(realPath);
        if (!file1.exists()) {
            file1.mkdir();
        }
        OutputStream outputStream = new FileOutputStream(realPath+"\\"+file1);
        byte[] date = new byte[1024];
        int i;
        while ((i=inputStream.read(date))!=-1){
            outputStream.write(date,0,i);
        }
        outputStream.close();
        inputStream.close();

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }
}
